"""
@author: wy
@file: lib.py
@time: 2025/1/8 14:40
"""
import json
import requests
# import config
from config import *
import time
#message --> dict
#{"@timestamp":"2025-01-07T08:30:36.957Z","@metadata":{"beat":"filebeat","type":"_doc","version":"7.17.26"},"log":{"offset":107866,"file":{"path":"/var/log/nginx/access.log"}},"message":"192.168.138.2 - - [07/Jan/2025:16:30:33 +0800] \"GET / HTTP/1.1\" 200 20 \"-\" \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0\" \"-\"","input":{"type":"log"},"ecs":{"version":"1.12.0"},"host":{"name":"kafka1"},"agent":{"name":"kafka1","type":"filebeat","version":"7.17.26","hostname":"kafka1","ephemeral_id":"9a7fbcef-e08a-4500-ba76-064e70f5eb6c","id":"d9b4e2b9-2543-44c6-b525-33418e79c72a"}}
def json_to_dict(message: str) ->dict:
    d1 = {}
    try:
         d1 = json.loads(message)
    except:
        print("传递非json格式字符串")
    return d1

def resolv_ip(ip):
    #使用requests库  -- 相当于python浏览器，请求网址
    url = IP_URL+ip
    response = requests.get(url)
    #print(  dir(response)  )
    #{"ip":"114.114.114.114","pro":"江苏省","proCode":"320000","city":"南京市","cityCode":"320100","region":"","regionCode":"0",
    # "addr":"江苏省南京市 电信","regionNames":"","err":""}
    prov = response.json().get("pro")
    isp = response.json().get("addr").split()[1]
    return prov,isp
#时间格式转换
def time_format(time_str):
    # 定义原始时间字符串
    # time_str = "07/Jan/2025:16:30:33"
    # 定义时间字符串对应的格式
    format_str = "%d/%b/%Y:%H:%M:%S"
    # 将时间字符串转换为结构化时间
    struct_time = time.strptime(time_str, format_str)
    result_time = time.strftime("%Y-%m-%d %H:%M:%S", struct_time)
    return result_time



#"192.168.138.2 - - [07/Jan/2025:16:30:33 +0800] \"GET / HTTP/1.1\" 200 20 \"-\" \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0\" \"-\""
def  handler_log(log_str):
    #默认空白进行切割
    log_lst = log_str.split()
    ip = log_lst[0]
    #[07/Jan/2025:16:30:33
    time_str = log_lst[3][1:]
    flow = log_lst[9]
    prov,isp = resolv_ip(ip)
    result_time = time_format(time_str)
    return result_time, ip, prov, isp, flow


